package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.CommentType;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.UserLike;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@DubboService
public class CommentApiImpl implements CommentApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 分页查询评论
     *
     * @param movementId
     * @param commentType
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Comment> findComments(String movementId,
                                      CommentType commentType,
                                      Integer page, Integer pagesize) {
        //1、构造查询条件
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(movementId)).and("commentType")
                        .is(commentType.getType()))
                .skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        //2、查询并返回
        return mongoTemplate.find(query, Comment.class);
    }

    /**
     * 发布评论，并获取评论数量
     *
     * @param comment
     * @return
     */
    @Override
    public Integer save(Comment comment) {
        //1、查询动态
        Movement movement = mongoTemplate.findById(comment.getPublishId(), Movement.class);
        //2、向comment对象设置被评论人属性
        if (movement != null) {
            comment.setPublishUserId(movement.getUserId());
        }
        //3、保存到数据库
        mongoTemplate.save(comment);
        //4、更新动态表中的对应字段
        Query query = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        //跟据获取到的数据判断用户执行的操作
        if (comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", 1);//点赞数
        } else if (comment.getCommentType() == CommentType.COMMENT.getType()) {
            update.inc("commentCount", 1);//评论数
        } else {
            update.inc("loveCount", 1); //喜欢数
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        //获取更新后的最新数据
        Movement andModify = mongoTemplate.findAndModify(query, update, options, Movement.class);
        //5、获取最新的评论数量，并返回
        Integer integer = andModify.statisCount(comment.getCommentType()) + 1;
        return integer;
    }

    /**
     * 通过评论人id、动态id和评论类型查询单个评论是否存在
     *
     * @param userId
     * @param movementId
     * @param like
     * @return
     */
    @Override
    public boolean findCommentByUserId(Long userId, String movementId, CommentType like) {
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(movementId))
                .and("commentType").is(like.getType());
        Query query = Query.query(criteria);
        return mongoTemplate.exists(query, Comment.class);
    }

    /**
     * 删除单个评论，并获取剩下的评论数量
     *
     * @param comment
     * @return
     */
    @Override
    public Integer remove(Comment comment) {
        Criteria criteria = Criteria.where("userId").is(comment.getUserId())
                .and("commentType").is(comment.getCommentType())
                .and("publishId").is(comment.getPublishId());
        Query query = Query.query(criteria);
        mongoTemplate.remove(query, Comment.class);
        //修改动态表中的总数量
        Query movementQuery = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if (CommentType.LIKE.getType() == comment.getCommentType()) {
            update.inc("likeCount", -1);
        } else if (CommentType.COMMENT.getType() == comment.getCommentType()) {
            update.inc("commentCount", -1);
        } else {
            update.inc("loveCount", -1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);//获取更新后的最新数据
        Movement modify = mongoTemplate.findAndModify(movementQuery, update, options, Movement.class);
        return modify.statisCount(comment.getCommentType());
    }

    /**
     * 查询单个评论详细信息
     *
     * @param commentId
     * @return
     */
    @Override
    public Comment getCommentByUserId(String commentId) {
        return mongoTemplate.findById(new ObjectId(commentId), Comment.class);
    }

    /**
     * 给评论点赞，并获取点赞数量
     *
     * @param comment
     * @return
     */
    @Override
    public Integer saveComment(Comment comment) {
        //1、查询评论
        Comment movement = mongoTemplate.findById(comment.getPublishId(), Comment.class);
        //2、向comment对象设置被评论人属性
        if (movement != null) {
            comment.setPublishUserId(movement.getUserId());
        }
        //3、保存到数据库
        mongoTemplate.save(comment);
        //4、更新动态表中的对应字段
        Query query = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        //跟据获取到的数据判断用户执行的操作
        if (comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", 1);//点赞数
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        //获取更新后的最新数据
        Comment andModify = mongoTemplate.findAndModify(query, update, options, Comment.class);
        //5、获取最新的评论数量，并返回
        return andModify.getLikeCount() + 1;
    }

    /**
     * 给评论取消点赞
     *
     * @param userId
     * @param commentId
     * @return
     */
    @Override
    public Integer removeComment(Long userId, String commentId) {
        //删除点赞信息
        Criteria criteria = Criteria.where("userId").is(userId).and("publishId").is(commentId);
        Query query = Query.query(criteria);
        mongoTemplate.remove(query, Comment.class);
        //更新点赞数量
        Query commentQuery = Query.query(Criteria.where("id").is(commentId));

        Comment andModify = mongoTemplate.findAndModify(commentQuery,
                new Update().inc("likeCount", -1), new FindAndModifyOptions(), Comment.class);
        return andModify.getLikeCount();
    }

    /**
     * 查询当前动态下一个人的喜欢和点赞
     *
     * @param id
     * @param userId
     * @return
     */
    @Override
    public List<Integer> getComment(ObjectId id, Long userId) {
        Criteria criteria = Criteria.where("userId").is(userId).and("publishId").is(id);
        Query query = Query.query(criteria);
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        List<Integer> collect = comments.stream().map(item -> item.getCommentType()).collect(Collectors.toList());
        return collect;
    }

    /**
     * 查询点赞评论列表
     *
     * @param userId
     * @param page
     * @param pagesize
     * @param commentType
     * @return
     */
    @Override
    public List<Comment> comments(Long userId, Integer page, Integer pagesize, Integer commentType) {
        Criteria criteria = Criteria.where("userId").is(userId).and("commentType").is(commentType);
        Query query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        log.info("================================================{}", comments.toString());
        return comments;
    }  /**
     * 查询喜欢列表
     * @param userId
     * @param page
     * @param pagesize
     * @param commentType
     * @return
     */

    /**
     * 查询喜欢列表
     *
     * @param userId
     * @param page
     * @param pagesize
     * @param commentType
     * @return
     */
    @Override
    public List<Comment> loves(Long userId, Integer page, Integer pagesize, Integer commentType) {
        Criteria criteria = Criteria.where("userId").is(userId).and("commentType").is(commentType);
        Query query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        log.info("================================================{}", comments.toString());
        return comments;
    }

    /**
     * 查询当前用户是否对某个人喜欢
     * @param userId
     * @param id
     * @return
     */
    @Override
    public Boolean findByUserIdAndPublishUserId(Long userId, Long id) {
        //查询当前用户是否对某个人喜欢
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("likeUserId").is(id).and("isLike").is(true);
        Query created = Query.query(criteria).with(Sort.by(Sort.Order.desc("created"))).limit(1);
        List<UserLike> list = mongoTemplate.find(created, UserLike.class);
        if(CollUtil.isEmpty(list)){
            return false;
        }
        return true;
    }
}